

using EOSDigital.API;
using EOSDigital.SDK;

        #region 相机相关

        #region Variables

        CanonAPI APIHandler;
        Camera MainCamera;
        CameraValue[] AvList;
        CameraValue[] TvList;
        CameraValue[] ISOList;
        List<Camera> CamList;
        bool IsInit = false;
        Bitmap Evf_Bmp;
        int LVBw, LVBh, w, h;
        float LVBratio, LVration;

        int ErrCount;
        object ErrLock = new object();
        object LvLock = new object();

        #endregion




        #region API Events

        private void APIHandler_CameraAdded(CanonAPI sender)
        {
            try { Invoke((Action)delegate { RefreshCamera(); }); }
            catch (Exception ex) { ReportError(ex.Message, false); }
        }

        private void MainCamera_StateChanged(Camera sender, StateEventID eventID, int parameter)
        {
            try { if (eventID == StateEventID.Shutdown && IsInit) { Invoke((Action)delegate { CloseSession(); }); } }
            catch (Exception ex) { ReportError(ex.Message, false); }
        }

        private void MainCamera_ProgressChanged(object sender, int progress)
        {
            try { Invoke((Action)delegate { MainProgressBar.Value = progress; }); }
            catch (Exception ex) { ReportError(ex.Message, false); }
        }

        private void MainCamera_LiveViewUpdated(Camera sender, Stream img)
        {
            try
            {
                lock (LvLock)
                {
                    Evf_Bmp?.Dispose();
                    Evf_Bmp = new Bitmap(img);
                }
                LiveViewPicBox.Invalidate();
            }
            catch (Exception ex) { ReportError(ex.Message, false); }
        }
        /// <summary>
        /// 下载图片到指定目录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="Info"></param>
        private void MainCamera_DownloadReady(Camera sender, DownloadInfo Info)
        {
            try
            {
                string dir = null;
                Invoke((Action)delegate { dir = SavePathTextBox.Text; });
                sender.DownloadFile(Info, dir);

                Invoke((Action)delegate { MainProgressBar.Value = 0; });

                this.lblcphomsg.Text = dir + "\\" + Info.FileName;
                if (this.rdoBackPic.Checked == true)
                {
                    this.oppositeImg.ShowLocalPic(this.lblcphomsg.Text);
                    this.oppositeImg.ShowImg = Image.FromFile(this.lblcphomsg.Text);
                    Upload("背面");
                }
                else if (this.rdoDetailsPic.Checked == true)
                {
                    this.detailsImg1.ShowLocalPic(this.lblcphomsg.Text);
                    this.detailsImg1.ShowImg = Image.FromFile(this.lblcphomsg.Text);
                    Upload("细节");
                }
                else
                {
                    this.PositiveImg.ShowLocalPic(this.lblcphomsg.Text);
                    this.PositiveImg.ShowImg = Image.FromFile(this.lblcphomsg.Text);
                    Upload("正面");
                }

            }
            catch (Exception ex) { ReportError(ex.Message, false); }
        }

        private void ErrorHandler_NonSevereErrorHappened(object sender, ErrorCode ex)
        {
            ReportError($"SDK Error code: {ex} ({((int)ex).ToString("X")})", false);
        }

        private void ErrorHandler_SevereErrorHappened(object sender, Exception ex)
        {
            ReportError(ex.Message, true);
        }

        #endregion

        #region Session

        private void SessionButton_Click(object sender, EventArgs e)
        {
            if (CameraListBox.SelectedIndex < 0)
            {
                MessageBox.Show("请连接相机并开机");
                return;
            }

            if (MainCamera?.SessionOpen == true)
            {
                CloseSession();

                try
                {
                    if (MainCamera.IsLiveViewOn) { MainCamera.StopLiveView(); }
                }
                catch (Exception ex) { ReportError(ex.Message, false); }
            }
            else
            {
                OpenSession();

                try
                {
                    if (!MainCamera.IsLiveViewOn)
                    {
                        MainCamera.StartLiveView();
                    }

                }
                catch (Exception ex) { ReportError(ex.Message, false); }
            }
        }

        private void RefreshButton_Click(object sender, EventArgs e)
        {
            try { RefreshCamera(); }
            catch (Exception ex) { ReportError(ex.Message, false); }
        }

        #endregion

        #region Settings
        /// <summary>
        /// 拍照
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TakePhotoButton_Click(object sender, EventArgs e)
        {
            if (SavePathTextBox.Text.Trim().Length < 2)
            {
                MessageBox.Show("请选择保存到电脑中的目录");
                return;
            }

            try
            {
                MainCamera.TakePhotoShutterAsync(); 
            }
            catch (Exception ex) { ReportError(ex.Message, false); }
        }

        private void AvCoBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (AvCoBox.SelectedIndex < 0) return;
                MainCamera.SetSetting(PropertyID.Av, AvValues.GetValue((string)AvCoBox.SelectedItem).IntValue);
            }
            catch (Exception ex) { ReportError(ex.Message, false); }
        }


        private void ISOCoBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (ISOCoBox.SelectedIndex < 0) return;
                MainCamera.SetSetting(PropertyID.ISO, ISOValues.GetValue((string)ISOCoBox.SelectedItem).IntValue);
            }
            catch (Exception ex) { ReportError(ex.Message, false); }
        }


        #endregion

        #region Live view


        private void LiveViewPicBox_SizeChanged(object sender, EventArgs e)
        {
            try
            {
                LVBw = LiveViewPicBox.Width;
                LVBh = LiveViewPicBox.Height;
                LiveViewPicBox.Invalidate();
            }
            catch (Exception ex) { ReportError(ex.Message, false); }
        }

        private void LiveViewPicBox_Paint(object sender, PaintEventArgs e)
        {
            if (MainCamera == null || !MainCamera.SessionOpen) return;

            if (!MainCamera.IsLiveViewOn)
            {
                e.Graphics.Clear(BackColor);
            }
            else
            {
                lock (LvLock)
                {
                    if (Evf_Bmp != null)
                    {
                        LVBratio = LVBw / (float)LVBh;
                        LVration = Evf_Bmp.Width / (float)Evf_Bmp.Height;
                        if (LVBratio < LVration)
                        {
                            w = LVBw;
                            h = (int)(LVBw / LVration);
                        }
                        else
                        {
                            w = (int)(LVBh * LVration);
                            h = LVBh;
                        }

                        e.Graphics.DrawImage(Evf_Bmp, 0, 0, w, h);
                        //e.Graphics.DrawImage(Evf_Bmp, 0, 0, LVBw, LVBh);
                    }
                }
            }
        }


        #endregion

        #region Subroutines

        private void CloseSession()
        {
            MainCamera.CloseSession();
            AvCoBox.Items.Clear();

            ISOCoBox.Items.Clear();
            SettingsGroupBox.Enabled = false;
            LiveViewGroupBox.Enabled = false;
            SessionButton.Text = "打开相机";
            SessionLabel.Text = "未选择相机";

        }

        private void FrmSampleDressPhotograph_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                IsInit = false;
                MainCamera?.Dispose();
                APIHandler?.Dispose();
            }
            catch (Exception ex) { ReportError(ex.Message, false); }
        }

        private void BrowseButton_Click(object sender, EventArgs e)
        {
            try
            {
                if (Directory.Exists(SavePathTextBox.Text)) SaveFolderBrowser.SelectedPath = SavePathTextBox.Text;
                if (SaveFolderBrowser.ShowDialog() == DialogResult.OK)
                {
                    SavePathTextBox.Text = SaveFolderBrowser.SelectedPath;

                    IniHelper.SetKeyVal(SampleDressManageRecordIniFilePath, SavePathTextBoxKeyVal, this.SavePathTextBox.Text);
                }
            }
            catch (Exception ex) { ReportError(ex.Message, false); }
        }

        /// <summary>
        /// 存储拍照数据
        /// </summary>
        BindingList<ClothesDetailEntity> detailList = new BindingList<ClothesDetailEntity>();

        /// <summary>
        /// 单据状态
        /// </summary>
        List<DictionariesEntity> dicOutInFStatusList;


        /// <summary>
        /// 测试拍照
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            SetInDetailList("","","");
        }

        /// <summary>
        /// 样衣拍照准备入库
        /// </summary>
        private void SetInDetailList(string ZhengMian,string BeiMian,string XiJie)
        {

            int ArchivesID = Convert.ToInt32(ArchivesView.GetRowCellValue(ArchivesView.FocusedRowHandle, (ArchivesView.Columns["ArchivesID"])));
            ArchivesEntity entity = BArchives.BLL.GetArchivesEntity(ArchivesID);

            DTCloth = this.PictureGrid.DataSource as DataTable;

            //  detailList =ModelConvertHelper<ClothesDetailEntity>.ConvertToModel(DTCloth).ToList();

            if (DTCloth != null && DTCloth.Rows.Count > 0)
            {

                string CmpStyleNo = this.DTCloth.Rows[0]["CmpStyleNo"].ToString();
                StyleInfoEntity styleInfo = BStyleInfo.BLL.GetModel(CmpStyleNo);
                //查询尺码（根据公司款号来查询）
                StyleInfoEntity SizeName = BStyleInfo.BLL.GetSizeName(CmpStyleNo);

                //根据条码查询样衣拍照字表的图片路径
                string BarCode = DTCloth.Rows[0]["ClothesNo"].ToString();
                //判断，防止出现重复拍照的情况
                ClothesDetailEntity cdE = detailList.Where(t => t.MaterielNo == entity.ClothesNo).FirstOrDefault();
                if (cdE != null && !string.IsNullOrEmpty(cdE.MaterielNo))
                {
                    int index = detailList.IndexOf(cdE);

                    //detailList.Remove(cdE);
                    if (ZhengMian != "")
                    {
                        //正面
                        detailList[index].YarnSize = ZhengMian;
                    }
                    if (BeiMian != "")
                    {
                        //背面
                        detailList[index].CylinderNo = BeiMian;
                    }
                    if (XiJie != "")
                    {
                        //细节
                        detailList[index].YarnType = XiJie;
                    }
                    //this.cGridClothList.RefreshDataSource();
                }
                else
                {

                    //插入数据
                    detailList.Insert(0, new ClothesDetailEntity()
                    {
                        //订单号
                        FromOrderNo = DTCloth.Rows[0]["OrderNo"].ToString(),
                        //样衣编号
                        MaterielNo = DTCloth.Rows[0]["ClothesNo"].ToString(),
                        //款式编号
                        StyleNo = DTCloth.Rows[0]["StyleNo"].ToString(),
                        //公司款号
                        CmpStyleNo = CmpStyleNo,
                        //样衣类型
                        Remarks2 = DTCloth.Rows[0]["ArchivesType"].ToString(),
                        //长短袖
                        Describe2 = DTCloth.Rows[0]["ClothesTypeName"].ToString(),
                        //版型
                        Remarks = DTCloth.Rows[0]["FashionTypeName"].ToString(),
                        //季度
                        Describe = DTCloth.Rows[0]["QuarterName"].ToString(),
                        //色号
                        CmpColorNo = DTCloth.Rows[0]["CmpColorNo"].ToString(),
                        //设计师
                        EmpName = styleInfo.EmpName,
                        //尺码
                        SizeName = SizeName != null ? SizeName.SizeName : "L",
                        //面料
                        MaterielName = styleInfo.MaterielName,
                        //成份
                        Ingredient = styleInfo.Ingredient,
                        //正面图
                        YarnSize = ZhengMian,
                        //背面图
                        CylinderNo = BeiMian,
                        //细节图
                        YarnType = XiJie
                    });
                }
                this.cGridClothList.DataSource = detailList;
            }
            else
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("此样衣编号档案不存在！");
            }
        }

        BindingList<ClothesDetailEntity> list = new BindingList<ClothesDetailEntity>();

        /// <summary>
        /// 出入库单据类型
        /// </summary>
        List<DictionariesEntity> dicOutInTypeList;
        /// <summary>
        /// 入库
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_RuKu_Click(object sender, EventArgs e)
        {
            //获取到出入库明细表
            list = detailList;
            if (list.Count <= 0 || list == null)
            {
                MessageBox.Show("请选择拍照对象！");
            }
            else
            {

                //获取出入库主表
                storageEntity = new StorageOutInEntity();
                if (lpeType.EditValue == null)
                {
                    MessageBox.Show("请选择入库属性！");
                }
                else
                {
                    if (wareHouseControl1.lpeCK.Text != null && wareHouseControl1.lpeCK.Text != "请您选择")
                    {
                        long Outintype = long.Parse(lpeType.EditValue.ToString());
                        storageEntity.Orderno = BStorageOutIn.BLL.CreateOrderNo(UserInfo.CmpID);
                        storageEntity.Createuserid = UserInfo.EmpID.ToString();
                        storageEntity.DepartId = UserInfo.DepartID;
                        storageEntity.RelatedunitMC = UserInfo.DepCodes;
                        storageEntity.RelatedunitID = UserInfo.DepartID;
                        storageEntity.RelatedunitType = UserInfo.UserName;
                        storageEntity.CreateUserName = UserInfo.UserName;
                        storageEntity.Fstatus = 0;
                        storageEntity.Outintime = DateTime.Now;
                        storageEntity.Createtime = DateTime.Now;
                        storageEntity.Remark = "";
                        storageEntity.OrderType = StringEnum.GetStringValue(EOrderType.InOrder);
                        storageEntity.Outintype = Outintype > 0 ? Outintype : 0;
                        storageEntity.SpeciesId = BDictionaries.BLL.GetDictID("91.009");
                        storageEntity.BillType = BDictionaries.BLL.GetDictID("350.005");
                        storageEntity.RDepartID = 0;
                        //仓库
                        string WareHouseDautm = wareHouseControl1.lpeCK.Text;
                        //仓区
                        string WareHouseCQ = "";
                        //仓位
                        string WareHouseCW = "";
                        if (wareHouseControl1.lpeCQ.Text == "请您选择" || wareHouseControl1.lpeCW.Text == "请您选择")
                        {
                            //仓区
                             WareHouseCQ = "";
                            //仓位
                             WareHouseCW = "";
                        }
                        else
                        {
                            //仓区
                             WareHouseCQ = wareHouseControl1.lpeCQ.Text;
                            //仓位
                             WareHouseCW = wareHouseControl1.lpeCW.Text;
                        }
                        bool flag = BClothesDetail.BLL.InsertClothesDetail(list, storageEntity, WareHouseDautm, WareHouseCQ, WareHouseCW);

                        if (flag)
                        {
                            MessageBox.Show("入库成功！");
                        }
                        else
                        {
                            MessageBox.Show("入库失败！");
                        }
                    }
                    else
                    {
                        MessageBox.Show("请选择仓库");
                    }
                }
            }
        }
        /// <summary>
        /// 选择行的单元格改变
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void gridView1_RowCellClick(object sender, DevExpress.XtraGrid.Views.Grid.RowCellClickEventArgs e)
        {
            try
            {
                string Img = "";
                if (e.Column.Caption == "正面图")
                {
                    Img = gridView1.GetFocusedRowCellValue("YarnSize").ToString();
                }
                else if (e.Column.Caption == "背面图")
                {
                    Img = gridView1.GetFocusedRowCellValue("CylinderNo").ToString();
                }
                else if (e.Column.Caption == "细节图")
                {
                    Img = gridView1.GetFocusedRowCellValue("YarnType").ToString();
                }
                else
                {
                    return;
                }
                SelectSingle(Img);
            }
            catch (Exception nn)
            {
                this.LiveViewPicBox.Image = null;
                return;
                throw;
            }
        }
        /// <summary>
        /// 数据回填，把图片放到LiveViewPicBox
        /// </summary>
        /// <param name="SelectRow"></param>
        private void SelectSingle(string SelectRow)
        {
            if (SelectRow == "")
            {
                return;
            }
            else
            {
                //调用工具类下的查看图片
                ChaKanPIC c = new ChaKanPIC();
                c.ChaKanPic(SelectRow);
            }
        }
        
        private void RefreshCamera()
        {
            CameraListBox.Items.Clear();
            CamList = APIHandler.GetCameraList();
            foreach (Camera cam in CamList) CameraListBox.Items.Add(cam.DeviceName);
            if (MainCamera?.SessionOpen == true) CameraListBox.SelectedIndex = CamList.FindIndex(t => t.ID == MainCamera.ID);
            else if (CamList.Count > 0) CameraListBox.SelectedIndex = 0;
        }

        private void OpenSession()
        {
            if (CameraListBox.SelectedIndex >= 0)
            {
                MainCamera = CamList[CameraListBox.SelectedIndex];
                MainCamera.OpenSession();
                MainCamera.LiveViewUpdated += MainCamera_LiveViewUpdated;
                MainCamera.ProgressChanged += MainCamera_ProgressChanged;
                MainCamera.StateChanged += MainCamera_StateChanged;
                MainCamera.DownloadReady += MainCamera_DownloadReady;

                SessionButton.Text = "关闭相机";
                SessionLabel.Text = MainCamera.DeviceName;
                AvList = MainCamera.GetSettingsList(PropertyID.Av);
                TvList = MainCamera.GetSettingsList(PropertyID.Tv);
                ISOList = MainCamera.GetSettingsList(PropertyID.ISO);
                foreach (var Av in AvList) AvCoBox.Items.Add(Av.StringValue);

                foreach (var ISO in ISOList) ISOCoBox.Items.Add(ISO.StringValue);
                AvCoBox.SelectedIndex = AvCoBox.Items.IndexOf(AvValues.GetValue(MainCamera.GetInt32Setting(PropertyID.Av)).StringValue);

                ISOCoBox.SelectedIndex = ISOCoBox.Items.IndexOf(ISOValues.GetValue(MainCamera.GetInt32Setting(PropertyID.ISO)).StringValue);
                SettingsGroupBox.Enabled = true;
                LiveViewGroupBox.Enabled = true;
                this.BrowseButton.Enabled = true;

                MainCamera.SetSetting(PropertyID.SaveTo, (int)SaveTo.Host);
                MainCamera.SetCapacity(4096, int.MaxValue);
            }
        }

        private void ReportError(string message, bool lockdown)
        {
            int errc;
            lock (ErrLock) { errc = ++ErrCount; }

            if (lockdown) EnableUI(false);

            if (errc < 4) MessageBox.Show(message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            else if (errc == 4) MessageBox.Show("Many errors happened!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

            lock (ErrLock) { ErrCount--; }
        }

        private void EnableUI(bool enable)
        {
            if (InvokeRequired) Invoke((Action)delegate { EnableUI(enable); });
            else
            {
                SettingsGroupBox.Enabled = enable;
                InitGroupBox.Enabled = enable;
                LiveViewGroupBox.Enabled = enable;
            }
        }

        #endregion        
        #endregion